package com.itheima.putige.putige.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.itheima.putige.putige.entity.Orders;
import com.itheima.putige.putige.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Copyright (C), 2021-2022
 * Author: 16372
 * Date: 2022/2/21 16:18
 * FileName: PayController
 * Description: 阿里云支付
 */
@RestController
public class PayController {
    @Autowired
    private OrderService orderService;
    // 商户appid
    private final String APP_ID = "2016110200786030";
    // 私钥 pkcs8格式的
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYiSEv2dD14eldQqWQxiDSPfJtEDR22Qh+ICcjo8ivJb4HqkkYAGiiXlG5UEuMHxm1lmM70/6/EOibQbEOa8EPmvTyiS8BaqJL8ARD2WgszgZohZURxgWJNmGU1xho9dMX+paWCOOlrGgVmiFK07wtnCop3YXJvAO+C6p7EU/V8g5q6rKsDPXMzp0XV3FjaGhjmfzZnEiTJRBx8WfYLT5QwVP1ksm4uMrJ5uIIK2g5vaYAhEFzzdiT/p2Ulu8cfP76SsrmtyT0/XZI1MtI8sBDJGAUuCbDFauN+6U6Y4+CqTEo2c/h1AAi7GIL4tL6Ed7hnrnK9xpbVHzFCMJGNdvDAgMBAAECggEAdAK3juEmoBt1lUx/B6DojX43xuMwQ8PFRcfGfMCwfSVDZikI9ow5CGSb20lKbAOrVgRO7M3LTh3aC1rnAoTJjMjZyyyy52zmisK9O606Ifl/vjb6rU3iH/2QMdd15T4xkmcv6GRSX0rEzsku0O5AjJ/dIYItosSwQ/Yzbu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
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtmFi2mY/Fuiu/1e3LA1tMdJjNNmmQ0zwOzG1ckCLWgsbPqvpuGnf4tkAni9vPWxuu1FAUBoPL2vcqL9GKLE4T+Spf7LrGT87RcjNurQWDGeIV4kOzp4hxLbCJOaPRhdh4daqnoDMFFqMRgJb2vZI/+Hb0uBmTp+cUknKu8IQ21xw5qjJ+NmdSesLoacY8JoBiyYF6imO2SGic5ZDWTxZFPK/G/CeMaRmqP5ZmvK9DjN4QCnngU2DIO4wdXvF+Hf5j41ncHxCNVpvF1ob3ai7stZCa9vfvk/Ukxyyt1fg2cAiKVrQyI2wwArguTSNZh3JLMDx3+TbeoHWJJCe+DgIuwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    // 返回格式
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://localhost:8080/returnUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/returnUrl";
    // 日志记录目录
    public static String log_path = "/log";
    // RSA2
    public static String SIGNTYPE = "RSA2";



    /**
     * @Author 16372
     * @Description //TODO 阿里支付功能
     * @Date 21:56 2022/2/21
     * @Param [httpResponse, id]
     * @return void
     **/
    @GetMapping("/aliapy/{id}")
    public void alipay(HttpServletResponse httpResponse,@PathVariable Long id) throws IOException {
        Orders orders = orderService.getById(id);

        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        Long out_trade_no = orders.getId();
        //付款金额，必填
        String total_amount = String.valueOf(orders.getAmount());
        //订单名称，必填
        String subject ="菩提阁消费";
        //商品描述，可空
        String body = LocalDateTime.now() + "的外卖订单";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * @Author 16372
     * @Description //TODO 支付成功的回调
     * @Date 20:23 2022/2/21
     * @Param [request, response]
     * @return java.lang.String
     **/
    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            Orders orders = new Orders();
            orders.setStatus(2);
            orders.setId(Long.valueOf(out_trade_no));
            orderService.updateById(orders);
            response.sendRedirect("/front/page/order.html");
            return "/front/page/order.html";//跳转付款成功页面
        }else{
            response.sendRedirect("/front/page/order.html");
            return "/front/page/order.html";//跳转付款失败页面
        }

    }



}
